<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 任务管理
 *
 * @icon fa fa-circle-o
 */
class Task extends Backend {

    /**
     * Task模型对象
     * @var \app\admin\model\Task
     */
    protected $model = null;

    public function _initialize() {
        parent::_initialize();
        $this->model = model('Task');
        $this->view->assign("pushPositionList", $this->model->getPushPositionList());
        $this->view->assign("taskStatusList", $this->model->getTaskStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    //商家资料
    public function setbusiness() {
        if ($this->request->isPost()) {
            $data['business_title'] = input('business_title');
            $data['link_phone'] = input('link_phone');
            $data['link_man'] = input('link_man');
            $data['business_address'] = input('business_address');
            $data['business_img'] = input('business_img');
            $data['updatetime'] = time();
            $data['cert_status'] = 0;
            \think\Db::name('business')->where(['admin_id' => $this->iAdminId])->update($data);
            $this->success('操作成功，等待审核',url('businessmanage/index'));
        }
        $businessInfo = \think\Db::name('business')->where(['admin_id' => $this->iAdminId])->find();

        $this->assign('data', $businessInfo);
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function index() {
        
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
             $otherwhere[] = ['a.admin_id', '=', $this->iAdminId];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null,$otherwhere);
            $total = $this->model
                    ->alias('a')
                    ->join('fa_business','fa_business.admin_id = fa_task.admin_id','left')
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->alias('a')
                    ->field('a.*,b.business_title')
                    ->where($where)
                    ->join('fa_business b','b.admin_id = a.admin_id','left')
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            if($list){
                foreach($list as &$val){
                    $val['now_admin_id'] = $this->iAdminId;
                    $val['complete_order_count'] = \think\Db::name('order')->where(['task_id'=>$val['task_id'],'order_status'=>20])->count();
                    $val['get_order_count'] = $val['origin_task_num'] - $val['task_num'];
                    //任务费=酬金x任务数+￥50.00x任务数（制作费）
                    $val['task_total_price'] = ($val['task_price'] * $val['origin_task_num']) + ($val['make_price'] * $val['origin_task_num']) - $val['back_price'];
                }
                unset($val);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add() {
        $xgpzInfo = \think\Db::name('configure')->where(['key'=>'xiangguanpeizhi'])->find();
        $arrXgpzInfo = json_decode($xgpzInfo['desc'],true);
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['task_no'] = 'R'. mt_rand(100, 999). mt_rand(100, 999);
                    $params['push_position'] = '1,2';
                    $params['origin_task_num'] = $params['task_num'];
                    if ($params['brand']) {
                        $params['car_brand_list'] = implode(',', $params['brand']);
                    }
                    if ($params['type']) {
                        $params['car_type_list'] = implode(',', $params['type']);
                    }
                    if ($params['color']) {
                        $params['car_color_list'] = implode(',', $params['color']);
                    }
                    if ($params['position_ids']) {
                        $params['position_ids'] = implode(',', $params['position_ids']);
                    } else {
                        $this->error('上刊网点必须选择');
                    }
                    $params['admin_id'] = $this->iAdminId;
                    $params['make_price'] = 50;
                    //判断是否首次任务-且后台开启奖励
                    $taskWhere['task_status']  = array('NOT IN',[6]);     //状态：1-待审核 2-待支付 3-待开始 4-展示中 5-已结束 6-已拒绝
                    $taskWhere['admin_id']  = $this->iAdminId;
                    $taskCount = \think\Db::name('task')->where($taskWhere)->count();
                    if($arrXgpzInfo['onoff_first_price'] == 1 && $taskCount == 0){
                        $params['back_price'] = $arrXgpzInfo['first_price'];
                    }
                    
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        
        //汽车品牌
        $brandList = \think\Db::name('car_brand')->where(['is_del' => 0])->order('car_brand_id ASC')->select();
        $colorList = \think\Db::name('car_color')->where(['is_del' => 0])->order('car_color_id ASC')->select();
        $typeList = \think\Db::name('car_type')->where(['is_del' => 0])->order('car_type_id ASC')->select();
        $positionList = \think\Db::name('position')->where(['is_del' => 0])->order('position_id ASC')->select();
        $this->assign('brandList', $brandList);
        $this->assign('colorList', $colorList);
        $this->assign('typeList', $typeList);
        $this->assign('positionList', $positionList);
        $this->assign('onoff_first_price', $arrXgpzInfo['onoff_first_price']);
        return $this->view->fetch();
    }
    
    public function over(){
        $task_id = input('task_id',0,'intval');
        $data['task_status'] = 5;
        \think\Db::name('task')->where(['task_id' => $task_id])->update($data);
        $this->success();
    }
    
    public function checkok(){
        $task_id = input('task_id',0,'intval');
        $data['task_status'] = 2;
        $data['check_time'] = time();
        \think\Db::name('task')->where(['task_id' => $task_id])->update($data);
        $this->success();
    }
    public function checkno(){
        $task_id = input('task_id',0,'intval');
        $data['refuse_text'] = input('refuse_text');
        $data['check_time'] = time();
        $data['task_status'] = 6;
        \think\Db::name('task')->where(['task_id' => $task_id])->update($data);
        $this->success();
    }
    
    public function paytask() {
        $admin_id = $this->iAdminId;
        $task_id = input('task_id');
        $taskInfo = \think\Db::name('task')->where(['task_id'=>$task_id,'admin_id'=>$admin_id])->find();
        if($taskInfo['task_status'] != 2){
            $this->error('支付任务不存在');
        }
        //商家
        $businessInfo = \think\Db::name('business')->where(['admin_id'=>$taskInfo['admin_id']])->find();
        $business_id = $businessInfo['business_id'];
        //任务费=酬金x任务数+￥50.00x任务数（制作费）
        $task_total_price = ($taskInfo['task_price'] * $taskInfo['origin_task_num']) + ($taskInfo['make_price'] * $taskInfo['origin_task_num']) - $taskInfo['back_price'];
                
        $walletInfo = \think\Db::name('business_wallet')->where(['business_id'=>$business_id])->find();
        
        if(empty($walletInfo)){
            $this->error('账户金额不足');
        }
        if(floatval($walletInfo['cash_amount']) < $task_total_price ){
            $this->error('账户金额不足');
        }
        \think\Db::startTrans();
        $walletLogRes = $this->change_business_wallet($business_id, 1, $task_total_price,1,array('task_id'=>$taskInfo['task_id']));
        if($walletLogRes){
            $saveTask['task_status'] = 3;
            $saveTask['updatetime'] = time();
            model('task')->where(['task_id'=>$task_id,'admin_id'=>$admin_id])->update($saveTask);
            \think\Db::commit();
            $this->success('支付成功');
        }else{
            \think\Db::rollback();
            $this->success('支付失败');
        }
        
    }
    
    public function detail(){
        $id = input('ids');
        $taskInfo = \think\Db::name('task')->where(['task_id'=>$id])->find();
        if(!empty($taskInfo)){
            $arr_position = [];
            if(!empty($taskInfo['push_position'])){
                $positionList = \think\Db::name('car_position')->where('car_position_id','in',$taskInfo['push_position'])->select();
                foreach($positionList as $val){
                    array_push($arr_position, $val['position_name']);
                }
            }
            $taskInfo['push_position'] = implode(',', $arr_position);
            
            $arr_brand = [];
            if(!empty($taskInfo['car_brand_list'])){
                $brandList = \think\Db::name('car_brand')->where(['car_brand_id'=>array('in',$taskInfo['car_brand_list'])])->select();
                foreach($brandList as $val){
                    array_push($arr_brand, $val['brand_name']);
                }
                $taskInfo['car_brand_list'] = implode(',', $arr_brand);
            }else{
                $taskInfo['car_brand_list'] = '全部';
            }

            $arr_color = [];
            if(!empty($taskInfo['car_color_list'])){
                $colorList = \think\Db::name('car_color')->where(['car_color_id'=>array('in',$taskInfo['car_color_list'])])->select();
                foreach($colorList as $val){
                    array_push($arr_color, $val['color_name']);
                }
                $taskInfo['car_color_list'] = implode(',', $arr_color);
            }else{
                $taskInfo['car_color_list'] = '全部';
            }

            $arr_type = [];
            if(!empty($taskInfo['car_type_list'])){
                $typeList = \think\Db::name('car_type')->where(['car_type_id'=>array('in',$taskInfo['car_type_list'])])->select();
                foreach($typeList as $val){
                    array_push($arr_type, $val['type_name']);
                }
                $taskInfo['car_type_list'] = implode(',', $arr_type);
            }else{
                $taskInfo['car_type_list'] = '全部';
            }

        }
        if($taskInfo){
            $taskInfo['xg_img'] = explode(',', $taskInfo['xg_img']);
        }
        $taskInfo['complete_order'] = \think\Db::name('order')->where(['task_id'=>$id,'order_status'=>20])->count();
        $wd_position = \think\Db::name('position')->where(['position_id'=>['in',$taskInfo['position_ids']]])->select();
        
        $taskInfo['wd_position'] = '';
        if(!empty($wd_position)){
            $arr_wd_position = [];
            foreach($wd_position as $val){
                $arr_wd_position[] = $val['position_name'];
            }
            $taskInfo['wd_position'] = implode(',', $arr_wd_position);
        }
        $this->assign('positionList', json_encode($positionList));
        $this->assign('positionCount', count($positionList));
        
        $this->view->assign('data', $taskInfo);
        return $this->view->fetch();
    }

}
